package com.sdx.console.system.web;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.console.service.OrgConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.common.QRCodeUtil;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.console.promote.entity.PromoteLink;
import com.sdx.console.promote.service.PromoteLinkService;
import com.sdx.console.system.entity.ChannelSet;
import com.sdx.console.system.entity.Export;
import com.sdx.console.system.entity.PromoteRecord;
import com.sdx.console.system.service.ChannelSetService;
import com.sdx.console.system.service.PromoteRecordService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 推广码 接口
 */
@RequestMapping("/system/promoteRecord")
@Controller
public class PromoteRecordController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(PromoteRecordController.class);
    private static final String MODEL = "/system/promoteRecord";


    @Resource
	private PromoteRecordService promoteRecordService;

    @Resource
    private ChannelSetService channelSetService;

	@Resource
	private OrgConsoleService orgConsoleService;

	@Resource
    private CorePlatformService corePlatformService;

	@Resource
    private CustomerInfoService customerInfoService;

	@Resource
    private PromoteLinkService promoteLinkService;

    @Autowired
    FileService fileService;

	/**
	 * 初始化页面需要的列表数据，
	 * @param view 业务模块，来源渠道
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
	    Integer accessType = corePlatformService.getAccessType(request);
		List<ChannelSet> channelList = channelSetService.selectAuthChannels(accessType, user.getOrgId(),user.getTenantId());
		view.addObject("channelList",channelList);
		view.addObject("accessType",accessType);

		if (accessType==6) {
            view.addObject("orgList", orgConsoleService.getOrgs());
        }
	}
	/* 页面 */

    @GetMapping("/index.do")
    @Function("system.promoteRecord.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        setPageParam(view,request);
        return view;
    }

	@GetMapping("/createLink.do")
	@Function("system.promoteRecord.link")
	@ResponseBody
	public ModelAndView createLink(String promoteCode,HttpServletRequest request) {
		ModelAndView view = new ModelAndView(MODEL+"/createLink.html");
		//渠道、公司、个人
		//渠道列表、推广码列表、链接列表
        PromoteRecord promoteRecord = new PromoteRecord();
        promoteRecord.setPage(1);
        promoteRecord.setLimit(1000);
//        PageQuery<PromoteRecord> page = getList(promoteRecord,request);

        CoreUser user = getLoginUser(request);
        promoteRecord.setTenantId(user.getTenantId());
        Integer accessType = corePlatformService.getAccessType(request);
        if (accessType==1) {
            promoteRecord.setUserId(user.getId().intValue());
        } else if (accessType==3) {
            promoteRecord.setOrgId(user.getOrgId().intValue());
        }
        PageQuery<PromoteRecord> page = promoteRecord.getPageQuery();
        promoteRecordService.queryByCondition(page);

        view.addObject("recordListJson", JSON.toJSONString(page.getList()));
        view.addObject("recordList",page.getList());
        view.addObject("linkList",promoteLinkService.selectValid(user.getTenantId()));
        view.addObject("linkListJson", JSON.toJSONString(promoteLinkService.selectValid(user.getTenantId())));
        view.addObject("promoteCode",promoteCode);
        view.addObject("accessType",accessType);
        List<ChannelSet> channelList = channelSetService.selectAuthChannels(accessType, user.getOrgId(),user.getTenantId());
        view.addObject("channelList",channelList);
        if (accessType==6) {
            view.addObject("orgList", orgConsoleService.getOrgs());
        }
		return view;
	}

    @GetMapping("/edit.do")
    @Function("system.promoteRecord.edit")
    @ResponseBody
    public ModelAndView edit(String promoteCode,HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        PromoteRecord promoteRecord = promoteRecordService.queryById(promoteCode);
        view.addObject("promoteRecord", promoteRecord);
        setPageParam(view,request);
		try {
			view.addObject("promoteRecordJson", JacksonUtils.toJsonString(promoteRecord,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("system.promoteRecord.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        setPageParam(view,request);
        return view;
    }

    private PageQuery getList(PromoteRecord condtion,HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
        Integer accessType = corePlatformService.getAccessType(request);
        if (accessType==1) {
            condtion.setUserId(user.getId().intValue());
        } else if (accessType==3) {
            condtion.setOrgId(user.getOrgId().intValue());
        }
        PageQuery page = condtion.getPageQuery();
        promoteRecordService.queryByCondition(page);
        return page;
    }
    /* ajax json */

    @PostMapping("/list.json")
    @Function("system.promoteRecord.query")
    @ResponseBody
    public JsonResult<PageQuery> list(PromoteRecord condtion,HttpServletRequest request)
    {
        return JsonResult.success(getList(condtion, request));
    }



    private JsonResult save(boolean isNew,PromoteRecord promoteRecord,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		if (StringUtils.isEmpty(promoteRecord.getPromoteName())) {
			promoteRecord.setPromoteName(promoteRecord.getPromoteCode());
		}
    	if (isNew) {
			String promoteCode = null;
			while(promoteCode==null) {
				promoteCode = Utils.getRandomStringByLength(10);
				if (promoteRecordService.selectCodeCount(promoteCode)>0) {
					promoteCode = null;
				}
			}
			Integer accessType = corePlatformService.getAccessType(request);
			if (accessType==null || 1==accessType) {
			    //个人
                String customerId = customerInfoService.getCustomerId(user.getId().intValue());
                promoteRecord.setCustomerId(customerId);
                promoteRecord.setPromoterType("a");
            }
            if (accessType==null || 3==accessType || 1==accessType) {
			    promoteRecord.setOrgId(user.getOrgId().intValue());
            }
            promoteRecord.setTenantId(user.getTenantId());
			promoteRecord.setPromoteCode(promoteCode);
			promoteRecord.setCreatedBy(user.getId().intValue());
			promoteRecord.setCreatedName(user.getName());
			promoteRecord.setCreatedTime(new Date());
			promoteRecordService.save(promoteRecord);
		} else {
			promoteRecord.setUpdatedBy(user.getId().intValue());
			promoteRecord.setUpdatedName(user.getName());
			promoteRecord.setUpdatedTime(new Date());
			promoteRecordService.updateTemplate(promoteRecord);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("system.promoteRecord.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)PromoteRecord promoteRecord,HttpServletRequest request
		)
    {
	    Integer accessType = corePlatformService.getAccessType(request);

	    if (accessType.intValue()==3) {
		    CoreUser user = getLoginUser(request);
		    promoteRecord.setOrgId(user.getOrgId().intValue());
	    }
        return save(true,promoteRecord,request
		);
    }

    @PostMapping("/update.json")
    @Function("system.promoteRecord.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  PromoteRecord promoteRecord,HttpServletRequest request
		) {
		return save(false,promoteRecord,request
		);
    }


   
    @GetMapping("/view.json")
    @Function("system.promoteRecord.query")
    @ResponseBody
    public JsonResult<PromoteRecord>queryInfo(String promoteCode) {
        PromoteRecord promoteRecord = promoteRecordService.queryById( promoteCode);
        return  JsonResult.success(promoteRecord);
    }

    @PostMapping("/delete.json")
    @Function("system.promoteRecord.del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        //List<Long> idList = ConvertUtil.str2longs(ids);
		List<String> idList = new ArrayList<String>();
		Collections.addAll(idList,ids.split(","));
        promoteRecordService.batchDelPromoteRecord(idList);
        return JsonResult.success();
    }

    @PostMapping("/getChannel.json")
    @ResponseBody
    public List<ChannelSet> channelList(HttpServletRequest request,Long orgId,Integer accessType ){
        CoreUser user = getLoginUser(request);
        Long orgid = user.getOrgId();
        if(accessType == 6){
            orgid = orgId;
        }
        List<ChannelSet> channelList = channelSetService.selectChannelSet(orgid);
        return channelList;
    }

    @PostMapping("/getRecord.json")
    @ResponseBody
    public List<PromoteRecord> getRecordList(HttpServletRequest request,Long orgId,Integer accessType,String channelCode){
        CoreUser user = getLoginUser(request);
        Long orgid = user.getOrgId();
        if(accessType == 6){
            orgid = orgId;
        }
        List<PromoteRecord> list = promoteRecordService.selectRecord(channelCode,orgid);
        return list;
    }


    @PostMapping("/export.json")
    @ResponseBody
    public JsonResult<String>  export(HttpServletRequest request,Long orgId,Integer accessType,String channelCode,String record,String link,String recordName){
        CoreUser user = getLoginUser(request);
        Long orgid = user.getOrgId();
        if(accessType == 6){
            orgid = orgId;
        }
        List<Export> dataList = new ArrayList<>();
        String dir = DateUtil.now("yyyyMMdd");
        String subPath = "/images/link/"+dir+"/";
        String path = FileUtils.getRoot()+subPath;
        if(StringUtils.isNotBlank(record)&&StringUtils.isNotBlank(link)){
            Export export = new Export();
            String url = link +"?"+record;
            if(link.indexOf("?")!=-1){
                url = link +"&"+record;
            }
            export.setName(recordName);
            export.setLink(url);
            try {
                Boolean encode = QRCodeUtil.encode(url, null, path, false, dir);
                if(encode){
                    InputStream imageInputStream = new FileInputStream(FileUtils.getRoot()+subPath+dir+".jpg");
                    byte[] bytes = Utils.input2byte(imageInputStream);
                    export.setImg(bytes);
                }
            }catch (Exception e){

            }
            dataList.add(export);
        }else if(StringUtils.isNotBlank(record)){
            List<PromoteLink> promoteLinks = promoteLinkService.selectValid(user.getTenantId());
            for (PromoteLink promoteLink : promoteLinks) {
                Export export = new Export();
                String url = promoteLink.getLinkAddr() +"?"+record;
                if(promoteLink.getLinkAddr().indexOf("?")!=-1){
                    url = promoteLink.getLinkAddr() +"&"+record;
                }
                export.setName(promoteLink.getLinkName());
                export.setLink(url);
                try {
                    Boolean encode = QRCodeUtil.encode(url, null, path, false, dir);
                    if(encode){
                        InputStream imageInputStream = new FileInputStream(FileUtils.getRoot()+subPath+dir+".jpg");
                        byte[] bytes = Utils.input2byte(imageInputStream);
                        export.setImg(bytes);
                    }
                }catch (Exception e){

                }
                dataList.add(export);
            }
        }else if(StringUtils.isNotBlank(link)){
            List<PromoteRecord> list = promoteRecordService.selectRecord(channelCode,orgid);
            for (PromoteRecord promoteRecord : list) {
                Export export = new Export();
                String url = link +"?"+"channel="+promoteRecord.getChannelCode()+"&comeFrom="+ promoteRecord.getPromoteCode();
                if(link.indexOf("?")!=-1){
                    url = link +"&"+"channel="+promoteRecord.getChannelCode()+"&comeFrom="+ promoteRecord.getPromoteCode();
                }
                export.setName(promoteRecord.getPromoteName());
                export.setLink(url);
                try {
                    Boolean encode = QRCodeUtil.encode(url, null, path, false, dir);
                    if(encode){
                        InputStream imageInputStream = new FileInputStream(FileUtils.getRoot()+subPath+dir+".jpg");
                        byte[] bytes = Utils.input2byte(imageInputStream);
                        export.setImg(bytes);
                    }
                }catch (Exception e){

                }
                dataList.add(export);

            }

        }




        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此exportTestService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate = "excelTemplates/system/record.xls";
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("推广码_"+ DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", dataList);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
    }
    

}
